<template>
  <div class="market-container">
    <!-- 顶部统计信息 -->
    <div class="market-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><ShoppingCart /></el-icon>
                <span>总挂单数</span>
              </div>
            </template>
            <div class="stat-value">{{ marketStats.totalListings }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><Money /></el-icon>
                <span>最低价格</span>
              </div>
            </template>
            <div class="stat-value">{{ formatPrice(marketStats.floorPrice) }} TRES</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><Histogram /></el-icon>
                <span>24h 交易量</span>
              </div>
            </template>
            <div class="stat-value">{{ formatPrice(marketStats.volume24h) }} TRES</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><TrendCharts /></el-icon>
                <span>我的挂单</span>
              </div>
            </template>
            <div class="stat-value">{{ marketStats.myListings }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 市场主体内容 -->
    <div class="market-content">
      <el-tabs v-model="activeTab" class="market-tabs">
        <el-tab-pane label="市场列表" name="market">
          <div class="market-toolbar">
            <el-input
              v-model="searchQuery"
              placeholder="搜索宝藏..."
              class="search-input"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="sortBy" placeholder="排序方式" class="sort-select">
              <el-option label="最新上架" value="latest" />
              <el-option label="价格从低到高" value="priceAsc" />
              <el-option label="价格从高到低" value="priceDesc" />
              <el-option label="稀有度" value="rarity" />
            </el-select>
            <el-select v-model="filterRarity" placeholder="稀有度" class="filter-select">
              <el-option label="全部" value="" />
              <el-option label="普通" value="普通" />
              <el-option label="罕见" value="罕见" />
              <el-option label="稀有" value="稀有" />
              <el-option label="史诗" value="史诗" />
              <el-option label="传说" value="传说" />
            </el-select>
          </div>
          <market-list 
            :items="filteredMarketItems"
            @buy="handleBuy"
            @view-details="showNFTDetails"
          />
        </el-tab-pane>
        <el-tab-pane label="我的上架" name="myListings">
          <my-listings 
            :items="myListedItems"
            @cancel="handleCancelListing"
            @view-details="showNFTDetails"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- NFT 详情弹窗 -->
    <el-dialog
      v-model="detailDialog.visible"
      :title="detailDialog.nft?.name || '宝藏详情'"
      width="600px"
      destroy-on-close
      class="nft-dialog"
    >
      <NFTDetail
        :nft="detailDialog.nft"
        :is-listed="detailDialog.isForSale"
        :is-owner="detailDialog.isOwner"
        @list="handleList"
        @buy="handleBuy"
        @cancel="handleCancelListing"
      >
        <span class="value price-value">{{ formatPrice(detailDialog.nft.price) }} TERS</span>
      </NFTDetail>
    </el-dialog>

    
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useWalletStore } from '../stores/walletStore';
import { 
  ShoppingCart, Money, Histogram, TrendCharts, Search 
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import MarketList from '../components/market/MarketList.vue';
import MyListings from '../components/market/MyListings.vue';
import NFTDetail from '../components/market/NFTDetail.vue';
import "../styles/MarketView.css"
import { ethers } from 'ethers';
const walletStore = useWalletStore();
const activeTab = ref('market');
const searchQuery = ref('');
const sortBy = ref('latest');
const filterRarity = ref('');

// 市场统计数据
const marketStats = ref({
  totalListings: 0,
  floorPrice: 0,
  volume24h: 0,
  myListings: 0
});

// 市场列表数据
const marketItems = ref([]);
const myListedItems = ref([]);

// 弹窗状态
const detailDialog = ref({
  visible: false,
  nft: null,
  isForSale: false,
  isOwner: false
});

const listDialog = ref({
  visible: false,
  form: {
    price: 0.001
  },
  loading: false,
  nft: null
});

// 格式化价格显示
const formatPrice = (price) => {
  console.log("价格为", price)
  // 直接返回整数格式
  return price;
};

// 过滤和排序市场列表
const filteredMarketItems = computed(() => {
  let items = [...marketItems.value];
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    items = items.filter(item => 
      item.name.toLowerCase().includes(query) ||
      item.rarity.toLowerCase().includes(query)
    );
  }
  
  // 稀有度过滤
  if (filterRarity.value) {
    items = items.filter(item => item.rarity === filterRarity.value);
  }
  
  // 排序
  switch (sortBy.value) {
    case 'priceAsc':
      items.sort((a, b) => a.price - b.price);
      break;
    case 'priceDesc':
      items.sort((a, b) => b.price - a.price);
      break;
    case 'rarity':
      const rarityOrder = ['Common',  'Rare', 'Epic', 'Legendary'];
      items.sort((a, b) => 
        rarityOrder.indexOf(b.rarity) - rarityOrder.indexOf(a.rarity)
      );
      break;
    default: // latest
      items.sort((a, b) => b.listTime - a.listTime);
  }
  
  return items;
});

// 显示 NFT 详情
const showNFTDetails = (nft) => {
  detailDialog.value = {
    visible: true,
    nft,
    isForSale: nft.isForSale,
    isOwner: nft.owner.toLowerCase() === walletStore.walletAddress.toLowerCase()
  };
};

// 处理上架
const handleList = (nft) => {
  listDialog.value = {
    visible: true,
    form: {
      price: 0.001
    },
    loading: false,
    nft
  };
};


// 处理购买
const handleBuy = async (nft) => {
  try {
    

    // 3. 检查代币余额
    const balance = await walletStore.tokenContract.balanceOf(walletStore.walletAddress);
    console.log("当前余额:", balance.toString());
    console.log("需要支付:", nft.price);
    
    if (balance.lt(ethers.BigNumber.from(nft.price))) {
      ElMessage.error('TRES代币余额不足！');
      return;
    }


    // 5. 显示确认对话框
    await ElMessageBox.confirm(
      `确认以 ${formatPrice(nft.price)} TRES 购买该宝藏？`,
      '购买确认',
      {
        confirmButtonText: '确认购买',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 6. 买家批准代币使用权限
    try {
      console.log("准备批准代币使用权限...");
      console.log("合约地址:", walletStore.contract.address);
      console.log("需要批准的金额:", nft.price);
      
      const approveTx = await walletStore.tokenContract.approve(
        walletStore.marketContract.address, 
        nft.price,
        { gasLimit: 100000 }
      );
      console.log("批准代币交易已发送:", approveTx.hash);
      await approveTx.wait();
      console.log("代币批准完成");
    } catch (approveError) {
      console.error("批准代币失败:", approveError);
      ElMessage.error('批准代币失败，请重试');
      return;
    }
    
    // 7. 执行购买
    try {
      console.log("开始执行购买...");
      console.log("NFT ID:", nft.id);
      const tx = await walletStore.marketContract.buyTreasure(nft.id);
      console.log("购买交易已发送:", tx.hash);
      
      await tx.wait();
      console.log("购买交易已确认");
      
      ElMessage.success('购买成功！');
      await refreshMarketData();
      detailDialog.value.visible = false;
    } catch (buyError) {
      console.error("购买交易失败:", buyError);
      ElMessage.error(`购买失败：${buyError.reason || buyError.message || '购买交易执行失败'}`);
    }
  } catch (error) {
    if (error === 'cancel') return;
    console.error('操作失败:', error);
    ElMessage.error(`操作失败：${error.reason || error.message || '未知错误'}`);
  }
};

// 处理取消上架
const handleCancelListing = async (nft) => {
  try {
    // 调用合约取消上架
    const tx = await walletStore.marketContract.cancelTreasureSale(nft.id);
    await tx.wait();
    
    ElMessage.success('取消上架成功！');
    await refreshMarketData();
    
    detailDialog.value.visible = false;
  } catch (error) {
    console.error('取消上架失败:', error);
    ElMessage.error('取消上架失败');
  }
};

// 刷新市场数据
const refreshMarketData = async () => {
  try {
    const [totalListings, floorPrice, volume24h] = await walletStore.marketContract.getMarketStats();
    marketStats.value.totalListings = totalListings;
    console.log("总挂单数为", totalListings);
    marketStats.value.floorPrice = floorPrice;
    console.log("最低价格为", floorPrice);
    marketStats.value.volume24h = volume24h;
    console.log("24小时交易量为", volume24h);
    const listings = await walletStore.marketContract.getAllListedNFTs();
    console.log("获取到的市场列表:", listings);

    marketItems.value = await Promise.all(
      listings.map(async (item) => {
        console.log("处理列表项:", item);
        const metadata = await walletStore.contract.tokenURI(item.id);
        console.log("获取到的metadata:", metadata);
        const data = await fetch(metadata).then(res => res.json());
        
        return {
          id: item.id.toString(),
          name: `数字宝藏  #${data.attributes[0].value} ${item.id}`,
          rarity: data.attributes[0].value,
          charm: data.attributes[1].value,
          image: `https://pink-obliged-bat-235.mypinata.cloud/ipfs/${data.image.slice(7)}`,
          price: item.salePrice.toString(),
          owner: item.seller,
          listTime: null,
          isForSale: item.isForSale,
          isSolved: item.isSolved,
        };
      })
    );
    console.log("处理后的市场列表:", marketItems.value);
    // 获取我的上架列表
    myListedItems.value = marketItems.value.filter(
      item => item.owner.toLowerCase() === walletStore.walletAddress.toLowerCase()
    );
    marketStats.value.myListings = myListedItems.value.length;
  } catch (error) {
    console.error('刷新市场数据失败:', error);
    ElMessage.error(`刷新市场数据失败: ${error.message || error}`);
  }
};

// 组件挂载时获取数据
onMounted(async () => {
  if (walletStore.isConnected) {
    await refreshMarketData();
  }
});

// 监听钱包连接状态
watch(() => walletStore.isConnected, async (newValue) => {
  if (newValue) {
    await refreshMarketData();
  }
});
</script>

<style scoped>
/* 添加确认框样式 */
.buy-confirm-dialog .confirm-content {
  margin: 20px 0;
  text-align: left;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.buy-confirm-dialog .confirm-content p {
  margin: 8px 0;
  color: #606266;
}

.buy-confirm-dialog .el-message-box__message {
  max-width: 100%;
}

/* 调整确认框按钮样式 */
.buy-confirm-dialog .el-message-box__btns {
  padding-top: 20px;
}

.buy-confirm-dialog .el-message-box__btns .el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.buy-confirm-dialog .el-message-box__btns .el-button--default {
  margin-right: 10px;
}
</style>
